package com.zhanlv.composer

import android.util.Log
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.lang.Exception
import java.net.Socket

class ServerWorkThread(private val socket: Socket): Thread() {
    private val inputStream: InputStream

    private val outputStream: OutputStream

    init {
        inputStream = socket.getInputStream()
        outputStream = socket.getOutputStream()
    }

    companion object{
        const val TAG = "SocketServer"
    }

    override fun run() {
        while (true){
            Log.w(TAG, "ServerThread run")
            try{
                val buffer = ByteArray(1024)

                Log.w(TAG, "inputStream available: ${inputStream.available()}")

                var length = inputStream.read(buffer)

                var payload = String(buffer, 0, length, Charsets.UTF_8)
                Log.w(TAG, "payload: $payload")

                SocketGateway.run(payload, object: SocketGateway.SocketGatewayInterface{
                    override fun onResult(res: String) {
                        sendToClient(res)
                    }
                })

            }catch (e: Exception){
                Log.e(TAG, "ServerThread run error: " + e.message)
            }
        }
    }

    private fun sendToClient(msg: String){
        if (socket.isClosed) return

        try {
            outputStream.write(msg.toByteArray())
            outputStream.flush()
        }catch (e: IOException){
            Log.e(TAG, "sendToClient error: " + e.message)
        }
    }
}